package com.sharding.demo.controller;

import com.sharding.demo.config.CloudHintShardingAlgorithm;
import com.sharding.demo.config.HintType;
import com.sharding.demo.config.HitManagerConfig;
import com.sharding.demo.entity.User;
import com.sharding.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.infra.hint.HintManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private HitManagerConfig hitManagerConfig;



    @Autowired
    private UserService userService;

    @PostMapping("/save")
    public String save(@RequestBody User user) {
        hitManagerConfig.initShardingSphere("11111");

        try{
            userService.save(user);
        }catch (Exception e){
            log.error("异常",e);
        }finally {
            //每次执行完sql，执行hintManager.close()，防止自动关闭失败
            hitManagerConfig.closeShardingSphere();
        }
        return "success";
    }

    @PostMapping("/delete")
    public String delete(@RequestParam(value = "id") Long id) {
        userService.delete(id);
        return "success";
    }

    @PostMapping("/update")
    public int update(@RequestBody User user) {
        return userService.update(user);
    }

    @GetMapping("/findAll")
    public List<User> findAll() {
        hitManagerConfig.initShardingSphere("11111");
        List<User> userList = userService.findAll();
        hitManagerConfig.closeShardingSphere();

        return userList;
    }

}
